<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="关键字" prop="custTaxcode" label-width="60px">
        <el-input
          style="width: 205px"
          v-model="queryParams.keyword"
          placeholder="请输入税号、名称或流水号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="制单日期" label-width="80px">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item
        label="状态"
        prop="checkStatus"
        label-width="60px"
        v-show="showT"
      >
        <el-select
          v-model="queryParams.checkStatus"
          placeholder="请选择"
          style="width: 130px"
        >
          <el-option
            v-for="item in stateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="订单来源"
        prop="resource"
        label-width="85px"
        v-show="showT"
      >
        <el-select
          v-model="queryParams.resource"
          placeholder="请选择"
          style="width: 110px"
        >
          <el-option
            v-for="item in orderSourceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="订单类型"
        prop="orderType"
        label-width="80px"
        v-show="showT"
      >
        <el-select
          v-model="queryParams.orderType"
          placeholder="请选择"
          style="width: 110px"
        >
          <el-option
            v-for="item in orderTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="合同上传查询"
        prop="htHas"
        label-width="100px"
        v-show="showT"
      >
        <el-select
          v-model="queryParams.htHas"
          placeholder="请选择"
          style="width: 165px"
        >
          <el-option
            v-for="item in uploadQueryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="所属分公司"
        prop="citycode"
        label-width="95px"
        v-show="showT"
      >
        <el-select
          v-model="queryParams.citycode"
          placeholder="请选择"
          style="width: 185px"
        >
          <el-option
            v-for="item in branchOfficeOptions"
            :key="item.codevalue"
            :label="item.codename"
            :value="item.codevalue"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="所属分类"
        prop="ssywbk"
        label-width="85px"
        v-show="showT"
      >
        <el-select
          v-model="queryParams.ssywbk"
          placeholder="请选择"
          style="width: 100px"
        >
          <el-option
            v-for="item in classificationOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="" @click="showT = !showT">{{
          showT == true ? '收缩' : '展开'
        }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="small"
          style="font-weight: bold"
          @click="addItem"
        >
          手工建单</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="small"
          style="font-weight: bold"
          @click="addDialogVisible = true"
        >
          批量导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="small"
          style="font-weight: bold"
          @click="handleCancel"
          v-loading="loadingCancel"
          :disabled="multiple"
          >批量作废</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
                <el-button type="primary" plain size="mini" style="font-weight: bold" @click="handleSync"
                    v-loading="loadingSync" :disabled="multiple">回款同步</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" plain size="mini" style="font-weight: bold" @click="handleExport"
                    v-loading="loadingSync">批量导出</el-button>
            </el-col> -->
    </el-row>

    <el-table
      @row-dblclick="dbSelected"
      v-loading="loading"
      :data="tableList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        align="center"
        width="50"
      ></el-table-column>
      <el-table-column
        label="流水号"
        prop="serialNo"
        width="200"
        align="center"
      />
      <el-table-column
        label="订单号"
        prop="orderNo"
        width="200"
        align="center"
      />

      <el-table-column
        label="订单来源"
        align="center"
        prop="resource"
        :show-overflow-tooltip="true"
        width="120"
      >
        <template #default="scope">
          <span v-if="scope.row.resource == 1">诺诺订单</span>
          <span v-else-if="scope.row.resource == 2">系统订单</span>
        </template>
      </el-table-column>
      <el-table-column
        label="订单类型"
        align="center"
        prop="orderType"
        :show-overflow-tooltip="true"
        width="120"
      >
        <template #default="scope">
          <span v-if="scope.row.orderType == 1">软件订单</span>
          <span v-else-if="scope.row.orderType == 2">硬件订单</span>
        </template>
      </el-table-column>
      <el-table-column
        label="制单时间"
        align="center"
        prop="createTime"
        :show-overflow-tooltip="true"
        width="200"
      />
      <el-table-column
        label="税号"
        align="center"
        prop="custTaxcode"
        width="180"
      />
      <el-table-column
        label="名称"
        align="center"
        prop="custName"
        width="160"
        show-overflow-tooltip
      />
      <el-table-column
        label="物品名称"
        align="center"
        prop="matNames"
        width="220"
      />
      <el-table-column
        label="总额"
        align="center"
        prop="totalAmount"
        width="50"
      />
      <el-table-column
        label="发票号"
        align="center"
        prop="billNo"
        width="160"
      />
      <el-table-column
        label="回款金额"
        align="center"
        prop="hkAmount"
        width="80"
      />
      <el-table-column
        label="剩余款项"
        align="center"
        prop="syAmount"
        width="160"
      />
      <el-table-column
        label="销售人员"
        align="center"
        prop="salesperson"
        width="160"
      />
      <el-table-column
        label="状态"
        align="center"
        prop="checkStatus"
        width="100"
      >
        <template #default="scope">
          <!-- 订单状态 -->
          {{ checkStatus_text(scope.row.checkStatus) }}
        </template>
      </el-table-column>
      <el-table-column
        label="合同是否上传"
        align="center"
        prop="htUrl"
        width="120"
      >
        <template #default="scope">
          <span v-if="scope.row.htUrl == null">否</span>
          <span v-else>是</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        prop="htUrl"
        width="100"
        fixed="right"
      >
        <template #default="scoped">
          <el-button
            v-if="
              scoped.row.checkStatus == '1' ||
              scoped.row.checkStatus == '2' ||
              scoped.row.checkStatus == '7'
            "
            size="small"
            link
            @click="updateOrder(scoped.row)"
            >编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 预览界面 -->
    <el-dialog
      :title="preview.title"
      v-model:visible="preview.open"
      width="80%"
      top="5vh"
      append-to-body
    >
      <el-tabs v-model="preview.activeName">
        <el-tab-pane
          v-for="(value, key) in preview.data"
          :label="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
          :key="key"
        >
          <pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!-- <import-table ref="import" @ok="handleQuery" /> -->

    <!-- 批量导入对话框 -->
    <el-dialog
      title="批量导入"
      v-if="addDialogVisible"
      v-model="addDialogVisible"
      width="400px"
    >
      <el-upload
        ref="upload"
        v-loading="upload.isUploading"
        element-loading-text="正在上传模板 请稍候"
        :limit="1"
        action="#"
        :http-request="requestAddUpload"
        accept=".xls"
        :disabled="upload.isUploading"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip" style="color: red">
            提示：仅允许导入“xlsx”格式文件！
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="fetchFile(2)"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script setup name="order">
import {
  fetchCityList,
  cancelOrder,
  copyOrder,
  createRedOrder,
  checkOrder,
  syncOrder,
  importOrderBranch
} from '@/api/order/order'
import {
  getMyOrderList,
  previewTable,
  delTable,
  genCode,
  synchDb,
  detailExport
} from '@/api/erp/orderManagement'
// import { downLoadZip } from "@/utils/zipdownload"
// import hljs from "highlight.js/lib/highlight"
// import "highlight.js/styles/github-gist.css"
// hljs.registerLanguage("java", require("highlight.js/lib/languages/java"))
// hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"))
// hljs.registerLanguage("html", require("highlight.js/lib/languages/xml"))
// hljs.registerLanguage("vue", require("highlight.js/lib/languages/xml"))
// hljs.registerLanguage("javascript",require("highlight.js/lib/languages/javascript"))
// hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"))

import {
  getCurrentInstance,
  onMounted,
  reactive,
  toRaw,
  toRefs,
  watch,
  computed
} from 'vue'

import { useRouter } from 'vue-router'
const { proxy } = getCurrentInstance()

const router = useRouter()
const route = useRouter()
const data = reactive({
  // 批量导入参数
  importDialogVisible: false,
  addDialogVisible: false,
  upload: {
    isUploading: false
  },
  loadingCancel: false,
  loadingSync: false,
  showT: false,
  // 遮罩层
  loading: true,
  // 唯一标识符
  uniqueId: '',
  // 选中数组
  ids: [],
  // 选中数组的状态
  checkStatus: [],
  // 选中表数组
  tableNames: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 表数据
  tableList: [],
  // 日期范围
  dateRange: [],
  // 查询参数
  queryParams: {
    startDate: undefined, //开始日期
    endDate: undefined, //结束日期
    checkStatus: undefined, //状态
    resource: undefined, //订单来源
    orderType: undefined, //订单类型
    ssywbk: undefined, //所属分类
    citycode: undefined, //所属分公司
    htHas: undefined, //合同是否上传查询
    serialNo: undefined, //流水号
    custName: undefined, //名称
    custTaxcode: undefined, //税号
    pageNum: 1,
    pageSize: 10
  },
  // 预览参数
  preview: {
    open: false,
    title: '代码预览',
    data: {},
    activeName: 'domain.java'
  },
  stateOptions: [
    {
      value: 1,
      label: '已提交'
    },
    {
      value: 2,
      label: '已审核'
    },
    {
      value: 3,
      label: '已同步A8'
    },
    {
      value: 4,
      label: '已完成'
    },
    {
      value: 5,
      label: '部分回款'
    },
    {
      value: 6,
      label: '未回款'
    },
    {
      value: 7,
      label: '审核不通过'
    },
    {
      value: 8,
      label: '同步失败'
    },
    {
      value: 9,
      label: '已作废'
    },
    {
      value: 10,
      label: '已红冲'
    }
  ],
  orderSourceOptions: [
    {
      value: 1,
      label: '诺诺订单'
    },
    {
      value: 2,
      label: '系统订单'
    }
  ],
  orderTypeOptions: [
    {
      value: 1,
      label: '软件订单'
    },
    {
      value: 2,
      label: '硬件订单'
    }
  ],
  classificationOptions: [
    {
      value: 1,
      label: '金税'
    },
    {
      value: 2,
      label: '税务'
    },
    {
      value: 3,
      label: '金融'
    }
  ],
  branchOfficeOptions: [],
  uploadQueryOptions: [
    {
      value: 1,
      label: '是'
    },
    {
      value: 0,
      label: '否'
    }
  ],
  selectList: []
})
const {
  addDialogVisible,
  upload,
  loadingCancel,
  loadingSync,
  showT,
  // 遮罩层
  loading,
  // 唯一标识符
  uniqueId,
  // 选中数组
  ids,
  // 选中数组的状态
  checkStatus,
  // 选中表数组
  tableNames,
  // 非单个禁用
  single,
  // 非多个禁用
  multiple,
  // 显示搜索条件
  showSearch,
  //表格数据
  tableList,
  // 导出遮罩层
  exportLoading,
  // 总条数
  total,
  // 查询参数
  queryParams,
  // 日期范围
  dateRange,
  preview,
  stateOptions,
  orderSourceOptions,
  orderTypeOptions,
  classificationOptions,
  branchOfficeOptions,
  uploadQueryOptions,
  selectList
} = toRefs(data)
// 订单状态
const checkStatus_text = computed(() => {
  return function (status) {
    switch (status) {
      case '1':
        return '已提交订单'
      case '2':
        return '已审核'

      case '3':
        return '已同步A8'

      case '4':
        return '已完成'

      case '5':
        return '部分回款'

      case '6':
        return '未回款'

      case '7':
        return '审核不通过'

      case '8':
        return '同步失败'

      case '9':
        return '已作废'

      case '10':
        return '已红冲'

      default:
        return ''
    }
  }
})
async function init() {
  // 获取城市列表
  let res = await fetchCityList()
  branchOfficeOptions.value = res.data
  await getList()
}
init()
// 获取城市列表
// function getfetchCityList() {
//     this.loading = true;
//     fetchCityList().then((response) => {
//         this.branchOfficeOptions = response.data;
//         this.loading = false;
//     });
// }

/** 查询表集合 */
function getList() {
  loading.value = true
  getMyOrderList(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    response => {
      tableList.value = response.rows
      total.value = response.total
      loading.value = false
    }
  )
}
/** 重置查询条件操作 */
function resetQuery() {
  dateRange.value = []
  queryParams.value = {
    pageNum: 1,
    pageSize: 10
  }
  getList()
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
/** 生成代码操作 */
function handleGenTable(row) {
  // const tableNames = row.tableName || this.tableNames;
  // if (tableNames == "") {
  //     this.msgError("请选择要生成的数据");
  //     return;
  // }
  // if (row.genType === "1") {
  //     genCode(row.tableName).then((response) => {
  //         this.msgSuccess("成功生成到自定义路径：" + row.genPath);
  //     });
  // } else {
  //     downLoadZip("/code/gen/batchGenCode?tables=" + tableNames, "ruoyi");
  // }
}
/** 同步数据库操作 */
function handleSynchDb(row) {
  const tableName = row.tableName
  // this.$confirm('确认要强制同步"' + tableName + '"表结构吗？', "警告", {
  //     confirmButtonText: "确定",
  //     cancelButtonText: "取消",
  //     type: "warning",
  // })
  //     .then(function () {
  //         return synchDb(tableName);
  //     })
  //     .then(() => {
  //         this.msgSuccess("同步成功");
  //     })
  //     .catch(() => { });
}
/** 打开导入表弹窗 */
function openImportTable() {
  proxy.$refs.import.show()
}

/** 预览按钮 */
function handlePreview(row) {
  previewTable(row.id).then(response => {
    preview.value.data = response.data
    preview.value.open = true
  })
}
/** 高亮显示 */
function highlightedCode(code, key) {
  // const vmName = key.substring(
  //     key.lastIndexOf("/") + 1,
  //     key.indexOf(".vm")
  // );
  // var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
  // const result = hljs.highlight(language, code || "", true);
  // return result.value || "&nbsp;";
}
// 多选框选中数据
function handleSelectionChange(selection) {
  console.log('selection', selection)
  selectList.value = selection
  ids.value = selection.map(item => item.id)
  checkStatus.value = selection.map(item => item.checkStatus)
  tableNames.value = selection.map(item => item.custName)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
//手工建单
function addItem() {
  router.push({
    path: '/xs/ddgl/newOrder',
    query: { id: '1' }
  })
}
// 修改订单按钮点击
function updateOrder(row) {
  if (!single.value)
    router.push({
      path: '/xs/ddgl/changeOrder',
      query: {
        flag: 'updateOrder',
        mark: 'myOrder',
        id: row.id,
        checkStatus: row.checkStatus
      }
    })
  else {
    proxy.$message({
      message: '请先选择一个订单',
      type: 'warning'
    })
  }
}

// 表格双击按钮
function dbSelected(row) {
  router.push({
    path: '/xs/ddgl/orderDetail',
    query: { flag: 'detail', htUrl: row.htUrl, id: row.id }
  })
}

/** 作废订单 */
function handleCancel() {
  loadingCancel.value = true
  cancelOrder({ ids: ids.value })
    .then(res => {
      if (res.code === 200) proxy.$modal.msgSuccess('操作成功')
      else proxy.$modal.msgError(res.msg)
      loadingCancel.value = false
      getList()
    })
    .catch(() => {
      loadingCancel.value = false
    })
}

/**回款同步 */
function handleSync() {
  let mark = 0
  // 3：已同步A8的、5：部分回款、6：未回款 这三种状态已经都允许回款审核
  // this.checkStatus.forEach((element) => {
  //     if (element != 3 && element != 5 && element != 6) {
  //         this.$message({
  //             message: "请选择状态是已同步A8的、部分回款或未回款的订单",
  //             type: "warning",
  //         });
  //     } else {
  //         mark++;
  //     }
  // });
  // if (mark == this.checkStatus.length) {
  //     this.loadingSync = true;
  //     syncOrder({ ids: this.ids }).then((res) => {
  //         if (res.code === 200) this.$message.success("操作成功");
  //         else this.$message.error(res.msg);
  //         this.loadingSync = false;
  //         this.getList();
  //     });
  // }
}
/**批量导出 */
function handleExport() {
  proxy
    .$confirm('是否确认导出所有数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      // return detailExport(this.queryParams, this.dateRange);
      return detailExport(queryParams.value, dateRange.value)
    })
    .then(response => {
      this.download(response.msg)
    })
    .catch(() => {})
}
/**下载模板 */
function fetchFile() {}
/** 下载模板操作 */
function importTemplate() {
  window.location.href = 'http://192.168.1.6:9000/erp/model/order/order.xls'
}
// 文件上传中处理
function handleFileUploadProgress(event, file, fileList) {
  upload.value.isUploading = true
}
// 文件上传成功处理
function handleFileSuccess(response, file, fileList) {
  upload.value.open = false
  upload.value.isUploading = false
  proxy.$refs.upload.clearFiles()
  proxy.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
  getList()
}
// 提交上传文件
function submitFileForm() {
  proxy.$refs.upload.submit()
}

async function requestAddUpload(data) {
  upload.value.isUploading = true
  let formData = new FormData()
  formData.append('file', data.file)
  try {
    const res = await importOrderBranch(formData)
    if (res.code === 200) {
      console.log(res)
    } else {
      // this.$message.error(res.msg);
      proxy.$modal.msgError(res.msg)
    }
    upload.value.isUploading = false
    addDialogVisible.value = false
    await getList()
  } catch (e) {
    console.log(e)
    // this.$message.error("上传文件服务异常 请重试");
    proxy.$modal.msgError('上传文件服务异常 请重试')
    upload.value.isUploading = false
  }
}
</script>
